package com.wzy.shirowebdemo.config;

import com.wzy.shirowebdemo.pojo.User;
import com.wzy.shirowebdemo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

public class MyRealm extends AuthorizingRealm {
    //SLJ4J日志门面
    Logger logger = LoggerFactory.getLogger(MyRealm.class);

    @Resource
    private UserService userService;

    /**
     * 自定义的授权方法
     * @param principalCollection 身份集合
     * @return 授权信息,返回给Shiro框架
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //该Shiro工具类通过ThreadLocal取出当前请求线程的Subject（主体）
        //
        Subject subject= SecurityUtils.getSubject();
        //从主体中取得User对象
        User user = (User) subject.getPrincipal();
        logger.debug("为用户{}执行授权逻辑.....",user.getUsername());
        //创建一个简单授权信息对象
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //封装来自数据库user表perms字段的权限值
        info.addStringPermission(user.getPerms());//user/add,user/update
        return info;
    }

    /**
     * 重写的自定义认证方法
     * @param authenticationToken 该认证Token对象封装了用户名、密码等信息
     * @return 认证信息
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证Token转换为常用的用户名密码Token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        logger.debug("为用户{}执行认证逻辑.....",token.getUsername());
        User user = userService.findByUserName(token.getUsername());
        if (user == null) {
            return null;//抛出用户不存在
        }
        //认证成功，返回一个封装后的简单认证信息对象
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
    }
}
